package com.hs.jhzd.repository;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.hs.jhzd.entity.ZfYyjlbEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Repository;
import com.hs.jhzd.entity.Meeting;

@Repository
public class MeetingNativeRepository {
	@PersistenceContext(unitName = "entityManagerFactory")
	private EntityManager em;

	public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
 
	/**
	 * 
	 * @param jsbh
	 * @param rybh
	 * @param name
	 * @param startTime
	 * @param endTime
	 * @param type
	 * @param done
	 * @return
	 */

	public List<Meeting> search(String jsbh, String rybh, String name,
								@DateTimeFormat(pattern = DATE_FORMAT) Date startTime, @DateTimeFormat(pattern = DATE_FORMAT) Date endTime,
								String type, Boolean isDisease, Boolean done) {
		final StringBuilder sql = new StringBuilder("SELECT  new com.hs.jhzd.entity.Meeting(u.zybh,u.yylx,u.yynr,u.yysj,u.rybh,u.xm, u.zt, u.zxsj) ");

		StringBuilder appendSql = new StringBuilder("FROM ZfYyjlbEntity u  ");

		appendSql.append("where 1=1 ");

		if (StringUtils.isNotBlank(jsbh)) {
			appendSql.append("AND u.jsbh= '" + jsbh + "' ");
		} else {
			throw new IllegalArgumentException("jsbh is null");
		}
		if (isDisease != null && isDisease) {
			appendSql.append("AND u.yylx = '0' ");
		} else {
			if (StringUtils.isNotBlank(type)) {
				appendSql.append("AND u.yylx = '" + type + "' ");
			} else {
				appendSql.append("AND u.yylx in ('1','2','3','4') ");
			}
		}
		if (name != null) {
			appendSql.append("AND u.xm = '" + name + "' ");
		}
		if (startTime != null) {
			SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String startTimeStr = formate.format(startTime);
			appendSql.append("AND u.yysj >= str_to_date('" + startTimeStr + "', '%Y-%m-%d %H:%i') ");

		}
		if (endTime != null) {
			SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String endTimeStr = formate.format(endTime);
			appendSql.append("AND u.yysj <=str_to_date('" + endTimeStr + "', '%Y-%m-%d %H:%i') ");
		}

		if (done != null) {
			appendSql.append("AND u.SCBJ =" + done + " ");
		}

		appendSql.append("ORDER BY u.sjc DESC");
		sql.append(appendSql);// 查询sql
		System.out.println(sql);
		Query query = em.createQuery(sql.toString());

		@SuppressWarnings("unchecked")
		List<Meeting> result = query.getResultList();

		return result;
	}
}
